<?php
/**
 * @Desc: Created by PhpStorm
 * @author: chenyuebin
 * @Time: 2022/2/14 0014   13:33
 */

namespace api\modules\v1\controllers\system\base;

use Yii;
use common\models\base\Drug;
use api\controllers\OnAuthController;
use services\base\DrugService;
use yii\web\HttpException;

class DrugController extends OnAuthController
{
    public $modelClass = '';

    /**
     * @Notes: 输液药品列表
     * @Interface actionIndex
     * @return array|\yii\data\ActiveDataProvider
     * @author: chenyuebin
     * @Time: 2022/2/14 0014   14:14
     */
    public function actionIndex()
    {
        $params = Yii::$app->request->get();

        $page = $params['page'] ?? 1;
        $pageSize = $params['pageSize'] ?? 10;

        // 查询结果
        $drugService = new DrugService();
        return $drugService->getListPage([], $page, $pageSize);
    }

    /**
     * @Notes:新增编辑输液药品
     * @Interface actionDrugSet
     * @return bool
     * @throws HttpException
     * @author: chenyuebin
     * @Time: 2022/2/14 0014   14:24
     */
    public function actionDrugSet()
    {
        $params = Yii::$app->request->post();
        $id = isset($params['id']) && $params['id'] ? $params['id'] : 0;
        $params['drug_type'] = $params['drug_type'] ?? 1;
        if (!isset($params['drug_name']) || !$params['drug_name']) {
            throw new HttpException(422, '请填写输液药品名称');
        }
        if (!isset($params['drug_unit']) || !$params['drug_unit']) {
            throw new HttpException(422, '请填写药品单位');
        }
        if (is_numeric($params['drug_unit'])) {
            throw new HttpException(422, '药品单位不合法【不得包含数字】');
        }

        $drugService = new DrugService();

        $condition = [
            'drug_name' => $params['drug_name'],
            'drug_type' => $params['drug_type'],
            'status' => [Drug::STATUS_INVALID, Drug::STATUS_ENABLE]
        ];
        if ($id) {
            $condition = [
                'and',
                $condition,
                ['!=', 'id', $id]
            ];
        }
        if ($drugService->drugInfo($condition)) {
            throw new HttpException(422, '该输液药品名称已存在');
        }

        return $drugService->drugSet($params, $id);
    }

    /**
     * @Notes:删除药品
     * @Interface actionDrugDel
     * @return int
     * @throws HttpException
     * @author: chenyuebin
     * @Time: 2022/2/14 0014   14:28
     */
    public function actionDrugDel()
    {
        $id = Yii::$app->request->get('id');
        if (!$id) {
            throw new HttpException(422, '请选择要删除的药品');
        }

        $drugService = new DrugService();
        return $drugService->Drugdel($id);
    }
}